﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using BartonExtension;

namespace SqliteWrapper.Procedures
{
    public class Proc_DeleteCategory : IProcedure
    {
        private bool deleteBook;
        public Proc_DeleteCategory(bool delBook)
            : base()
        {
            deleteBook = delBook;
        }
        public override SqliteError doProcedure(object DataSource, string DBPath)
        {
            Category category = DataSource as Category;
            SqliteError error = new SqliteError() { ErrorText = null, IsProcessSuccess = false };
            SqliteConnectionManager manager = SqliteConnectionManager.Create(DBPath);
            using (SQLiteWriteLock locker = new SQLiteWriteLock(manager.ConnectionString))
            {
                using (SQLiteConnection conn = manager.GetSqliteConnection())
                {
                    conn.Open();
                    using (SQLiteCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "delete from Category where ID = @ID";
                        cmd.Parameters.Add("@ID", System.Data.DbType.Int64).Value = category.ID;
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            error.ErrorText = ex.Message;
                        }
                    }

                    if (error.ErrorText.isNullOrEmpty())
                    {
                        using (SQLiteTransaction trans = conn.BeginTransaction())
                        {
                            using (SQLiteCommand cmd = conn.CreateCommand())
                            {
                                cmd.CommandText = "delete from Book where cid = @CID";
                                cmd.Parameters.Add("@CID", System.Data.DbType.Int64).Value = category.ID;
                                cmd.ExecuteNonQuery();
                            }
                        }
                    }
                }
            }
            return error;
        }
    }
}
